module coordinate_gen(
    input             clk               ,
    input             rst_n             ,
    
    input             per_frame_vsync  ,
    input             per_frame_href   , 
    input             per_frame_valid  ,

    output reg        post_frame_vsync  ,
    output reg        post_frame_href   , 
    output reg        post_frame_valid  ,

    output     [9:0]  pixel_xpos_w      ,
    output     [9:0]  pixel_ypos_w
);

reg        per_frame_href_d0;

wire       per_frame_href_pos;
wire       per_frame_href_neg;

reg [10:0] pixel_xpos       ;
reg [10:0] pixel_ypos       ;

assign pixel_xpos_w = pixel_xpos[9:0];
assign pixel_ypos_w = pixel_ypos[9:0];

assign per_frame_href_pos = per_frame_href & !per_frame_href_d0;
assign per_frame_href_neg = !per_frame_href & per_frame_href_d0;

always @(posedge clk or negedge rst_n) begin
    if(~rst_n)begin
        per_frame_href_d0 <= 1'd0;
    end
    else begin
        per_frame_href_d0 <= per_frame_href;
    end
end

//??????????
reg        cmos_frame_vsync_d0;

wire       cmos_frame_vsync_neg;

assign cmos_frame_vsync_neg = ((!per_frame_vsync) & cmos_frame_vsync_d0);

always @(posedge clk or negedge rst_n) begin
    if(~rst_n)begin
        cmos_frame_vsync_d0 <= 1'd0;
    end
    else begin
        cmos_frame_vsync_d0 <= per_frame_vsync;
    end
end

//lag 1 clock
always @(posedge clk or negedge rst_n) begin
    if(!rst_n)begin
        post_frame_vsync <= 1'd0;
        post_frame_href  <= 1'd0;
        post_frame_valid <= 1'd0;
    end
    else begin
        post_frame_vsync <= per_frame_vsync;
        post_frame_href  <= per_frame_href ;
        post_frame_valid <= per_frame_valid;
    end
end

always@(posedge clk or negedge rst_n)begin
    if(!rst_n)begin
        pixel_xpos <= 1'd0;
    end
    else if (per_frame_href_pos) begin
        pixel_xpos <= 1'd0;
    end
    else if(per_frame_href && per_frame_valid)begin
        pixel_xpos <= pixel_xpos + 1'd1;
    end
    else begin
        pixel_xpos <= pixel_xpos;
    end
end

always@(posedge clk or negedge rst_n)begin
    if(!rst_n)begin
        pixel_ypos <= 1'd0;
    end
    else if(cmos_frame_vsync_neg)begin
        pixel_ypos <= 1'd0;
    end
    else if(per_frame_href_neg)begin
        pixel_ypos <= pixel_ypos + 1'd1;
    end
    else begin
        pixel_ypos <= pixel_ypos;
    end
end

endmodule
